The Date object is a built-in object in JavaScript used for working with dates and times. You
create an instance of it using the new keyword.
There are several ways to create a new date object:
// 1. Current date and time
const now = new Date();
document.write("Current Time:", now);
// 2. Using a specific date string
const specificDate = new Date("2025-01-15T10:30:00");
document.write("Specific Date:", specificDate);
// 3. Using numbers (year, month, day, hours, minutes, seconds)
// Note: Month is 0-indexed (0 = January)
const eventDate = new Date(2025, 0, 20, 14, 0, 0);
document.write("Event Date:", eventDate.toLocaleString());
These methods are used to retrieve parts of a date.
const d = new Date();
document.write("Full Year:", d.getFullYear()); // e.g., 2024
document.write("Month (0-11):", d.getMonth()); // e.g., 6 for July
document.write("Date of Month:", d.getDate()); // e.g., 15
document.write("Day of Week (0-6):", d.getDay()); // 0 for Sunday
document.write("Hours:", d.getHours());
document.write("Minutes:", d.getMinutes());
document.write("Seconds:", d.getSeconds());
document.write("Milliseconds since epoch:", d.getTime());
JavaScript provides methods to format dates into more readable strings.
const d = new Date();
document.write("toDateString:", d.toDateString());
document.write("toLocaleDateString:", d.toLocaleDateString());
document.write("toLocaleString:", d.toLocaleString());
The Math object is a built-in, static object that has properties and methods for
mathematical constants and functions. You don't create an instance of it; you use it directly.
document.write("Math.round(4.7):", Math.round(4.7)); // 5
document.write("Math.ceil(4.2):", Math.ceil(4.2)); // 5 (rounds up)
document.write("Math.floor(4.9):", Math.floor(4.9)); // 4 (rounds down)
document.write("Math.pow(2, 3):", Math.pow(2, 3)); // 8 (2 to the power of 3)
document.write("Math.sqrt(64):", Math.sqrt(64)); // 8 (square root)
Math.random() returns a random floating-point number between 0 (inclusive) and 1 (exclusive).
// Random number between 0 and 1
document.write("Random float:", Math.random());
// Random integer between 1 and 10
let randomInt = Math.floor(Math.random() * 10) + 1;
document.write("Random integer (1-10):", randomInt);
document.write("Math.max(10, 5, 20):", Math.max(10, 5, 20)); // 20
document.write("Math.min(10, 5, 20):", Math.min(10, 5, 20)); // 5
document.write("Math.abs(-5):", Math.abs(-5)); // 5 (absolute value)
document.write("Value of PI:", Math.PI); // 3.14159...
| Feature | Date Object | Math Object |
|---|---|---|
| Object Creation | Requires instantiation (new Date()) |
Static object (used directly) |
| Purpose | Working with dates and times | Performing mathematical calculations |
| Example Usage | const d = new Date(); d.getFullYear(); |
Math.random(); |
Date (e.g., new Date()),
but Math is a static object used directly (e.g., Math.random()).
Test your understanding of JavaScript Date & Math.
getDaysDifference(date1, date2).